package com.itheima.reggie.service.impl;

import cn.hutool.db.sql.Order;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrderDetailMapper;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.*;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;


@Slf4j
@Service
@Transactional
public class OrderServiceImpl extends ServiceImpl <OrderMapper, Order> implements OrderService {
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private OrderMapper orderMapper;

   /* A. 获得当前用户id, 查询当前用户的购物车数据

    B. 根据当前登录用户id, 查询用户数据

    C. 根据地址ID, 查询地址数据

    D. 组装订单明细数据, 批量保存订单明细

    E. 组装订单数据, 批量保存订单数据

    F. 删除当前用户的购物车列表数据*/

    /**
     * 提交订单
     * @param orders
     */
    @Override
    public void submit(Orders orders) {
        //获得当前用户id, 查询当前用户的购物车数据
        //可判断是否为空，抛出异常
        Long userid = UserHolder.get();
        LambdaQueryWrapper<ShoppingCart> qw = new LambdaQueryWrapper<>();
        qw.eq(ShoppingCart::getUserId,userid);
        List<ShoppingCart> list = shoppingCartService.list(qw);
        if(list == null || list.size() == 0) {
            throw new CustomException("购物车为空，不能下单");
        }
        //根据当前登录用户id, 查询用户数据
        User user = userService.getById(userid);
        //根据地址ID, 查询地址数据
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);
        long orderId = IdWorker.getId();//订单号
        //总价
        BigDecimal amount = new BigDecimal(0);
        //保存订单明细数据：点了哪些菜品或套餐
        for (ShoppingCart shoppingCart : list) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(list,orderDetail);
            //orderId单独设置
            orderDetail.setOrderId(orderId);
            // amount 单独设置 数量 * 单价
            BigDecimal price = shoppingCart.getAmount();
            BigDecimal number =new BigDecimal(shoppingCart.getNumber());
            orderDetail.setAmount(price.multiply(number));
            amount.add(orderDetail.getAmount());
            orderDetailMapper.insert(orderDetail);
        }
        //组装订单信息
        orders.setId(orderId);//订单id
        orders.setOrderTime(LocalDateTime.now());//订单创建时间
        orders.setCheckoutTime(LocalDateTime.now());//订单结账时间
        orders.setStatus(2);//1待付款，2待派送，3已派送，4已完成，5已取消
        orders.setAmount(amount);//总金额
        orders.setUserId(userid);//用户id
        orders.setNumber(String.valueOf(orderId));//订单号
        orders.setUserName(user.getName());//用户名
        orders.setConsignee(addressBook.getConsignee());//收货人
        orders.setPhone(addressBook.getPhone());//收货人联系电话
        orders.setAddress(
                (addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                        + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                        + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                        + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));//省+市+区域+详细地址
        orderMapper.insert(orders);
    }
}
